package com.chinacreator.galaxylive.wx;

import com.chinacreator.galaxylive.wx.WxConfig;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * 微信模块出来服务
 * 使用方法请参考 https://github.com/Wechat-Group/weixin-java-tools
 */
@Service
public class WxService extends WxMpServiceImpl {

    @Autowired
    private WxConfig wxConfig;

    private final String WX_USER = "wx_user";


    @PostConstruct
    public void init() {
        //进行分布式部署需要重写 WxMpInMemoryConfigStorage 将token持久化
        final WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(this.wxConfig.getAppid());// 设置微信公众号的appid
        config.setSecret(this.wxConfig.getAppsecret());// 设置微信公众号的app corpSecret
        config.setToken(this.wxConfig.getToken());// 设置微信公众号的token
        config.setAesKey(this.wxConfig.getAesKey());// 设置消息加解密密钥
        config.setOauth2redirectUri(this.wxConfig.getOauth2redirectUri());
        super.setWxMpConfigStorage(config);
    }

    /**
     * 获取当前微信用户信息
     * 如果要分布式部署，需要把这块持久化（会过期的那种）
     * @param request
     * @return
     */
    public WxMpUser getWxMpUser(HttpServletRequest request){
        return (WxMpUser) request.getSession().getAttribute(WX_USER);
    }
    public void setWxMpUser(HttpServletRequest request,WxMpUser wxMpUser){
        request.getSession().setAttribute(WX_USER,wxMpUser);
    }


}
